package com.xinou.daily_report.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinou.common.base.config.ApiResponse;
import com.xinou.common.base.exception.BusException;
import com.xinou.common.util.BeanUtil;
import com.xinou.daily_report.PO.daily.DailyCommentAddPO;
import com.xinou.daily_report.PO.daily.DailyCommentListPO;
import com.xinou.daily_report.PO.daily.DailyReplyPO;
import com.xinou.daily_report.PO.daily.MyCommentListPO;
import com.xinou.daily_report.VO.DailyCommentInfoVO;
import com.xinou.daily_report.VO.MyCommentListVO;
import com.xinou.daily_report.entity.SysDaily;
import com.xinou.daily_report.entity.SysDailyComment;
import com.xinou.daily_report.mapper.SysDailyCommentMapper;
import com.xinou.daily_report.service.SysDailyCommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinou.daily_report.service.SysDailyService;
import com.xinou.daily_report.utils.ConstUtil;
import com.xinou.daily_report.utils.DailyShiroUtil;
import com.xinou.sso.dto.UserDTO;
import com.xinou.sso.service.SysUserService;
import com.xinou.sso.util.ShiroUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author lcc
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysDailyCommentServiceImpl extends ServiceImpl<SysDailyCommentMapper, SysDailyComment> implements SysDailyCommentService {

    final SysDailyService sysDailyService;
    final SysUserService sysUserService;

    @Override
    public ApiResponse<DailyCommentInfoVO> dailyCommentList(DailyCommentListPO po) {
        if (po.getDailyId() == null) {
            throw new BusException("条件错误");
        }
        List<SysDailyComment> dailyCommentList = list(new LambdaQueryWrapper<SysDailyComment>().eq(
                SysDailyComment::getDailyId, po.getDailyId()
        ));
        Map<Long, UserDTO> userDtoByUserIds = sysUserService.getUserDtoByUserIds(dailyCommentList.stream().map(SysDailyComment::getCommentUserId).collect(Collectors.toSet()));

        List<DailyCommentInfoVO> dailyCommentInfoList = BeanUtil.listA2ListB(dailyCommentList, DailyCommentInfoVO.class);
        for (DailyCommentInfoVO dailyCommentInfoVO : dailyCommentInfoList) {
            LocalDate date = dailyCommentInfoVO.getCommentDate();
            UserDTO commentUserDto = userDtoByUserIds.get(dailyCommentInfoVO.getCommentUserId());
            UserDTO replyUserDto = userDtoByUserIds.get(dailyCommentInfoVO.getReplyUserId());
            String commentUser=null;
            String replyUser=null;
            String replyUserIcon=null;
            String commentUserIcon=null;
            if(commentUserDto!=null){
                commentUser=commentUserDto.getRealName();
                commentUserIcon=commentUserDto.getIcon();
            }
            if(replyUserDto!=null){
                replyUser=replyUserDto.getRealName();
                replyUserIcon=replyUserDto.getIcon();
            }
            dailyCommentInfoVO
                    .setCanReply(date.equals(LocalDate.now()) || date.equals(LocalDate.now().minusDays(1)))
                    .setReplyUser(replyUser)
                    .setReplyUserIcon(replyUserIcon)
                    .setCommentUserIcon(commentUserIcon)
                    .setCommentUser(commentUser);
        }
        return new ApiResponse<>(dailyCommentInfoList);
    }

    @Override
    public ApiResponse<String> dailyComment(DailyCommentAddPO po) {
        SysDaily sysDaily = sysDailyService.getById(po.getDailyId());
//        if (!sysDaily.getDailyTime().equals(LocalDate.now()) &&
//                !sysDaily.getDailyTime().equals(LocalDate.now().minusDays(1))) {
//            throw new BusException("只能评论今天或者昨天的日报！");
//        }
        Boolean needReply = !sysDaily.getWorkerId().equals(ShiroUtil.getUserId())&&DailyShiroUtil.isLead();
        if (!save(BeanUtil.beanA2beanB(po, SysDailyComment.class)
                        .setReplyUserId(sysDaily.getWorkerId())
                        .setCommentUserId(ShiroUtil.getUserId())
                        .setNeedReply(needReply)
                        .setDailyWorkerId(sysDaily.getWorkerId())
                        .setCommentDate(LocalDate.now())
                )) {
            throw new BusException("添加评论失败");
        }
        if (!sysDaily.getStatus().equals(ConstUtil.DAILY_ALREADY_COMMENT)&&needReply) {
            sysDailyService.updateById(sysDaily.setStatus(ConstUtil.DAILY_ALREADY_COMMENT));
        }
        return new ApiResponse<>("评论成功");
    }

    @Override
    public ApiResponse<String> dailyReply(DailyReplyPO po) {
        SysDailyComment dailyComment = getById(po.getCommentId());
        if (po.getCommentId() == null || po.getReplyMessage() == null || dailyComment == null) {
            throw new BusException("回复失败");
        }
        SysDaily sysDaily = sysDailyService.getById(dailyComment.getDailyId());
        if (!dailyComment.getReplyUserId().equals(ShiroUtil.getUserId())) {
            throw new BusException("不能帮别人回复！");
        }
//        if (!dailyComment.getCommentDate().equals(LocalDate.now()) &&
//                !dailyComment.getCommentDate().equals(LocalDate.now().minusDays(1))) {
//            throw new BusException("不在评论时间内！");
//        }
        if (!updateById(dailyComment
                        .setIsReply(true)
                        .setReplyMessage(po.getReplyMessage())
                        .setReplyDate(LocalDate.now())
                )) {
            throw new BusException("添加评论失败");
        }
        if (count(new LambdaQueryWrapper<SysDailyComment>()
                .eq(SysDailyComment::getDailyId, sysDaily.getId())
                .eq(SysDailyComment::getIsReply, false)
                .eq(SysDailyComment::getNeedReply, true)) == 0) {
            sysDailyService.updateById(sysDaily.setStatus(ConstUtil.DAILY_ALREADY_REPLY));
        }
        return new ApiResponse<>("回复成功！");
    }

    @Override
    public ApiResponse<MyCommentListVO> myCommentList(MyCommentListPO po) {
        Long userId = ShiroUtil.getUserId();
        Page<SysDailyComment> page = new Page<>(po.getPageNumber(), po.getPageSize());
        Page<SysDailyComment> commentPage = page(page, new LambdaQueryWrapper<SysDailyComment>()
                .eq(SysDailyComment::getCommentUserId, userId));
        List<SysDailyComment>commentList = commentPage.getRecords();
        Map<Long, String> realNameByUserIds = sysUserService.getRealNameByUserIds(commentList.stream().map(k -> k.getDailyWorkerId()).collect(Collectors.toSet()));
        List<MyCommentListVO> commentVoList = commentList.stream().map(k -> new MyCommentListVO(k.getDailyId(), k.getCommentDate(), realNameByUserIds.get(k.getDailyWorkerId()))).collect(Collectors.toList());
        return new ApiResponse<>(commentVoList,commentPage.getTotal());
    }
}
